<?php

namespace App\Http\Controllers;

use App\Test1214;
use Illuminate\Http\Request;

class Test1214Controller extends Controller
{
    /**
     * 第一次获取用户信息
     * @param Request $request
     * @return array
     */
    public function getUserInfo(Request $request){
        $appid     = 'wx24a48c7871526b4e';
        $appsecret = 'b29d1ad5bcbd6dbb420d3806c55d543a';
        $code      = $request['code'];
        $url       = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$appsecret&js_code=$code&grant_type=authorization_code";
        $data      = file_get_contents($url);
        $openid    = json_decode($data,true);
        $where['openid'] = $openid['openid'];
        $ret       = Test1214::getOne($where);
        if(!$ret){
            $res = Test1214::addOne($where);
            if($res){
                return ['data'=>$openid,'code'=>0,'msg'=>'成功!'];
            }
        }else{
            return ['data'=>$openid,'code'=>0,'msg'=>'成功!'];
        }
    }

    /**
     * 第一次修改用户信息
     * @param Request $request
     * @return array
     */
    public function upUserInfo(Request $request){
        $where['openid']   = $request['openid'];
        $data['nickname']  = $request['nickname'];
        $data['image']     = $request['image'];
        if($request['sex'] == '1'){
            $data['sex'] = '先生';
        }else{
            $data['sex'] = '女士';
        }
        $res = Test1214::upOne($where,$data);
        if($res){
            return ['data'=>$data,'code'=>0,'msg'=>'修改成功'];
        }else{
            return ['data'=>'','code'=>1,'msg'=>'修改失败'];
        }
    }

    /**
     * 获取用户信息
     * @param Request $request
     * @return array
     */
    public function getInfo(Request $request){
        $where['openid'] = $request['openid'];
        $data = Test1214::getOne($where);
        return ['data'=>$data,'code'=>0,'msg'=>'查询成功'];
    }

    /**
     * 修改用户信息
     * @param Request $request
     */
    public function upInfo(Request $request){
        $where['openid']  = $request['openid'];
        if($request['nickname']){
            $data['nickname'] = $request['nickname'];
        }
        if($request['phone']){
            $data['phone']    = $request['phone'];
        }
        if($request['sex']){
            $data['sex']      = $request['sex'];
        }
        if($request['age']){
            $data['age']      = $request['age'];
        }
        $res = Test1214::upOne($where,$data);
        if($res){
            return ['data'=>$data,'code'=>0,'msg'=>'修改成功'];
        }else{
            return ['data'=>'','code'=>1,'msg'=>'修改失败'];
        }
    }
}
